package belf.migrate.engine.admin.handler;

import belf.migrate.api.table.dbtype.DBTypes;
import belf.migrate.api.table.dbtype.DBTypesHolder;
import belf.migrate.api.util.EngineConf;
import belf.migrate.core.util.ConfigUtil;
import belf.migrate.engine.BelfEvn;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import spark.Request;
import spark.Response;

import static spark.Spark.get;
import static spark.Spark.post;

public class ConfigHandler {
    private static Gson gson = new Gson();

    public static void setupRoutes() {
        get("/list", (request, response) -> {
            return list(request, response);
        });

        post("/dbtypes", (request, response) -> {
            return dbtype(request, response);
        });
    }

    private static String list(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        JsonObject jsonResponse = new JsonObject();
        String json = "{}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(EngineConf.getInstance().getConf());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    private static JsonObject dbtype(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        // 解析 JSON 字符串为 JsonObject
        JsonObject jsonObject = JsonParser.parseString(request.body()).getAsJsonObject();
        String catalog = jsonObject.get("catalog").getAsString();
        DBTypes dbTypes = DBTypesHolder.getInstance().getDBTypes(catalog);
        if (dbTypes == null) {
            return new JsonObject();
        } else {
            return dbTypes.toJson();
        }
    }
}
